﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Ldt.DataEngine.DataFlowParse.Model;
using LDT.CoreLibrary;
using LdtDataEngin.ModuleDetail.AnalysisModule.PersonnelAnalysis;
using LdtDataEngin.ModuleDetail.BaseModule;
using LdtDataEngin.ModuleDetail.PersonnelAnalysis.PersonnelModel.Personnel;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.DataModel.DataParseStorage;
using LdtJudge.DataEngine.Model.LogicblockServers;
using Newtonsoft.Json;

namespace LdtDataEngin.ModuleDetail.PersonnelAnalysis.PersonnelModel
{
    /// <summary>
    /// 人员节点信息
    /// </summary>
    public class PersonnelStart
    {
        public string xmlConfig;
        public string MatchParameterStr = "Prosecutor=2,89,164;Accused=1,90;Defender=168,169,13,99,100,101,102,103;Proxy=170,171,172,173,178,180;ProseProxy=2,89,164;AccusedProxy=1,90;Judger=t1,t2,t5,t4,t9;clerk=t6;";
        private DataContext _dataContext;

        private string _moduleName;
        public PersonnelStart(DataContext dataContext,string moduleName)
        {
            _dataContext = dataContext;
            _moduleName = moduleName;
        }

        /// <summary>
        /// 提取人员信息
        /// </summary>
        public void Extract()
        {
            #region 人员信息添加
            List<An_anjianshiti> anjianshitiList = new List<An_anjianshiti>();
            An_anjianshiti anjianshiti = new An_anjianshiti();
            #endregion

            #region 对应人员信息
            string conn=ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("ArtificialIntelligence");
            //获取案件中人员基础信息
            Dictionary<string, string> paragraphCode = PersonneSuitpartCode(_dataContext.DataLayerAns.Duanluos);

            foreach (KeyValuePair<string, string> code in paragraphCode)
            {
                string[] SDP_ParagraphCodes = code.Value.Split(',');
                string contents = "";
                foreach (string paragraphcode in SDP_ParagraphCodes)
                {
                    An_duanluo duanluo = _dataContext.DataLayerAns.Duanluos.FirstOrDefault(a => a.Duanluobianhao.ToLower() == paragraphcode.ToLower());
                    List<An_duanluo> duanluoList = _dataContext.DataLayerAns.Duanluos.Where(a => a.Duanluobianhao.ToLower() == paragraphcode.ToLower()).ToList();
                    if (duanluo != null)
                    {
                        foreach (An_duanluo item in duanluoList)
                        {
                            duanluo = item;
                            string value = duanluo.Duanluoneirong;
                            if (string.IsNullOrEmpty(contents))
                            {
                                contents = value;
                            }
                            else
                            {
                                contents = contents + "\r\n" + value;
                            }
                        }

                    }
                }
                string textformater = @"(?<=[^。\.；：])(?<!号|诉书|检察院|此致|(?<=此致[^\r]*\r[^\r]*)法院|附：|(?:检察员|核对无)[^\r\n]+|诉状)\r\n";
                contents = new Regex(textformater).Replace(contents, "");
                //获取人员实体
                PersonPostModle personPostModle = new PersonPostModle();
                personPostModle.id = Snowflake.Instance().GetId().ToString();
                personPostModle.modelCode = code.Key.Split('@')[1];
                personPostModle.content = contents.Trim();
                string message = HttpHelp.CreatePostHttpResponse(ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("ArtificialIntelligence") + "/api/entityrecognition/paragraphanalysis", JsonConvert.SerializeObject(personPostModle));
                PiecewiseResults piecewiseResults = JsonConvert.DeserializeObject<PiecewiseResults>(message);
                List<EntityResult> entityResultsList = new List<EntityResult>();
                if (piecewiseResults.Result.Code == "1")
                {
                    entityResultsList = JsonConvert.DeserializeObject<List<EntityResult>>(piecewiseResults.Body.ToString());
                    PersonnelFill(entityResultsList, code.Key.Split('@')[0]);
                }
            }
            #endregion

            _dataContext.InteractiveShow.LogShow("人员信息分析完毕:" + JsonConvert.SerializeObject(_dataContext.DataLayerAns.Anjianshitis));
            PersonnelBaseClass personnelBaseClass = new PersonnelBaseClass(_dataContext) { xmlconfig = xmlConfig };
            personnelBaseClass.Loade();

        }

        #region 人员对象提取
        /// <summary>
        /// 填充人员实体内容
        /// </summary>
        /// <param name="entityResultsList"></param>
        private void PersonnelFill(List<EntityResult> entityResultsList, string dictionaryKey)
        {
            string caseetiyinfoid = "";
            string caseAngerid = "";
            foreach (EntityResult entity in entityResultsList)
            {
                //人员基础信息
                An_anjianshiti anjianshiti = new An_anjianshiti();
                EntityResultItem entityResultItem = entity.Results.FirstOrDefault(a => a.Key == "name");
                if (entityResultItem != null)
                {
                    anjianshiti.Anjianshitiid = Snowflake.Instance().GetId().ToString();
                    anjianshiti.Mingcheng = entityResultItem.Content;
                    An_anjianshitijuese juese = new An_anjianshitijuese();
                    juese.Anjianshitiid = anjianshiti.Anjianshitiid;
                    juese.Jueseid = Snowflake.Instance().GetId().ToString();
                    EntityResultItem attendStateItem = entity.Results.FirstOrDefault(a => a.Key == "appearcourtcondition");
                    if (attendStateItem != null)
                        anjianshiti.Chutingqk = attendStateItem.Content;
                    int index = entity.Results.IndexOf(entityResultItem);
                    List<EntityResultItem> entityResults = entity.Results.Where(a => a.Key.IndexOf("suitdegree") > -1).ToList();
                    if (entityResults.Count > 0)
                    {
                        juese.Juesesusongdiwei = DictionariesConver.DictionaryValue(entityResults[0].Content);
                        juese.Juesexuhao = PersonnelReadIndex(juese.Juesesusongdiwei);
                        juese.SusongDiwei = entityResults[0].Content;
                        juese.Juesemingcheng = GetArgumentValueByMatchWords(MatchParameterStr, juese.Juesesusongdiwei);
                        if (juese.Juesesusongdiwei == "90" || juese.Juesesusongdiwei == "89"
                            || juese.Juesesusongdiwei == "1" || juese.Juesesusongdiwei == "7" ||
                            juese.Juesesusongdiwei == "13" || juese.Juesesusongdiwei == "155" ||
                            juese.Juesesusongdiwei == "156" || juese.Juesesusongdiwei == "157" ||
                            juese.Juesesusongdiwei == "19" || juese.Juesesusongdiwei == "29"
                            )
                        {
                            caseetiyinfoid = juese.Juesesusongdiwei;
                            caseAngerid = anjianshiti.Anjianshitiid;
                            juese.Zhuzhangfangleixing = "";
                        }
                        else
                        {
                            juese.Zhuzhangfangleixing = caseetiyinfoid;
                            juese.Zhuzhangfangjihe = caseAngerid;

                        }
                        // 对角色的当事人类型赋值
                        juese.Dangshirenleixing = GetPartiesType.Extract(entity.OriginalText);
                        if (_dataContext.DataLayerAns.Anjianshitis == null)
                        {
                            _dataContext.DataLayerAns.Anjianshitis = new List<An_anjianshiti>();
                        }
                        if (anjianshiti.Anjianshitijueses==null)
                        {
                            anjianshiti.Anjianshitijueses = new List<An_anjianshitijuese>();
                        }
                        anjianshiti.Anjianshitijueses.Add(juese);
                        if (_dataContext.DataLayerAns.Anjianshitijueses==null)
                        {
                            _dataContext.DataLayerAns.Anjianshitijueses = new List<An_anjianshitijuese>();
                        }
                        _dataContext.DataLayerAns.Anjianshitijueses.Add(juese);                        
                        if (_dataContext.DataLayerAns.Anjianshitis?.FirstOrDefault(a => a.Mingcheng == anjianshiti.Mingcheng) == null)
                        {
                            _dataContext.DataLayerAns.Anjianshitis.Add(anjianshiti);
                        }
                    }
                }
            }
        }


        public void PersonngNode(XmlNode xmlNode, string paragraphcode)
        {
            XmlNode xmlNode1row = xmlNode.SelectSingleNode("row");
            string oregtext = "";
            An_duanluo duanluo = _dataContext.DataLayerAns.Duanluos.FirstOrDefault(a => a.Duanluobianhao.ToLower() == paragraphcode.ToLower());
            List<An_duanluo> duanluos = _dataContext.DataLayerAns.Duanluos.Where(a => a.Duanluobianhao.ToLower() == paragraphcode.ToLower()).ToList();
            if (duanluo != null)
            {
                foreach (An_duanluo item in duanluos)
                {
                    duanluo = item;
                    string value = duanluo.Duanluoneirong;
                    if (string.IsNullOrEmpty(oregtext))
                    {
                        oregtext = value;
                    }
                    else
                    {
                        oregtext = oregtext + "\r\n" + value;
                    }
                }

            }
            //string rowscode = xmlNode1row.Attributes["code"].Value;

            //foreach (XmlNode xmlNodeFile in xmlNode1row.ChildNodes)
            //{

            //}


        }
        /// <summary>
        /// 根据匹配内容获取参数值
        /// </summary>
        /// <param name="matchKeyWords">匹配内容</param>
        /// <param name="originalValue">原始值</param>
        /// <returns>参数值</returns>
        public static string GetArgumentValueByMatchWords(string matchKeyWords, string originalValue)
        {
            string fieldValue = originalValue;
            matchKeyWords = Regex.Replace(matchKeyWords, @"(?<=;)\s", "", RegexOptions.Singleline);
            if (matchKeyWords != string.Empty)
            {
                fieldValue = (fieldValue == string.Empty) ? "空" : fieldValue;
                string paternStr = "(?<=^|；|;)[^=]+(?==(?:[^=；;]*[,，]*?)(?<![\u4E00-\u9FFF\r，、]){MatchKeyWord}[,;；])";
                string currPatern = paternStr.Replace("{MatchKeyWord}", fieldValue);
                string extractValue = Regex.Match(matchKeyWords.Replace("\r", ""), currPatern, RegexOptions.Singleline).Value.Trim(); //返回匹配到的编号值！
                if (extractValue == string.Empty && fieldValue != "空")
                {
                    //01.假如当前匹配值，满足1）未匹配成功。2）本身就是匹配字典值中的一个。则直接返回。
                    if (Regex.IsMatch(matchKeyWords, @"(?:^|;)" + originalValue + "="))
                    {
                        return originalValue;
                    }
                    //02.上述没匹配成功，则再进行其他匹配。
                    currPatern = paternStr.Replace("{MatchKeyWord}", "其他");
                    extractValue = Regex.Match(matchKeyWords, currPatern, RegexOptions.Singleline).Value;    //返回匹配到的编号值！
                    extractValue = extractValue.Replace("\r", "");//2017-09-12 ljx 添加提取出来的结果存在 ”\r\r\r内容“这样的类型值
                }
                if (extractValue == string.Empty)
                {
                    return "";
                }
                else
                {
                    return extractValue;
                }
            }
            return originalValue;
        }
        /// <summary>
        /// 诉讼地位查询
        /// </summary>
        /// <param name="index">人员提取位置</param>
        /// <param name="resultItemsList">诉讼地位集合</param>
        /// <returns></returns>
        private EntityResultItem PersonneSuitDegree(int index, List<EntityResultItem> resultItemsSuitDegreeList, List<EntityResultItem> entityResultsList)
        {
            foreach (EntityResultItem entit in resultItemsSuitDegreeList)
            {
                int suitindex = entityResultsList.IndexOf(entit);
                if (index > suitindex)
                {
                    return entit;
                }
            }
            return null;
        }

        /// <summary>
        /// 获取人员段落编号
        /// </summary>
        /// <returns></returns>
        private Dictionary<string, string> PersonneSuitpartCode(List<An_duanluo> duanluoList)
        {
            Dictionary<string, string> re = new Dictionary<string, string>();
            string partXPath = @"/" + _dataContext.DataLayerAns.CaseType + @"/" + _dataContext.DataLayerAns.SourceCode.ToLower();
            string xml = "";
            var configModel = _dataContext.DataLayerSys.GetConfigModel(_moduleName);
            ConfigModel configDetail = configModel.ConfigDetail.FirstOrDefault(a => a.ExecuteCode.ToLower().IndexOf("entityparagraphsource") > -1);
            if (configDetail!=null && !string.IsNullOrWhiteSpace(configDetail.ConfigContent))
            {
                xml = configDetail.ConfigContent;
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);
                XmlNode rootNode = doc.SelectSingleNode("/root/parties[@type='" + _dataContext.DataLayerAns.CaseType + "']");
                foreach (XmlNode item in rootNode.ChildNodes)
                {
                    string personelType = rootNode.Attributes["mqcode"].Value;
                    XmlNodeList targetNodes = doc.SelectNodes(@"/root/" + rootNode.Name + partXPath);
                    if (targetNodes.Count > 0)
                    {
                        if (_dataContext.DataLayerAns.CaseType.ToLower() == "a1")
                        {
                            re.Add(rootNode.Attributes["configeName"].Value + "@" + personelType, targetNodes[0].Attributes["paragCode"].Value);

                        }
                        else
                        {
                            re.Add(rootNode.Attributes["configeName"].Value + "@" + personelType, targetNodes[0].Attributes["paragCode"].Value);

                        }
                    }


                }

                //XmlNode rootANode = doc.SelectSingleNode("/root/judge");
                //if (rootANode!=null)
                //{
                //    foreach (XmlNode item in rootANode.ChildNodes)
                //    {
                //        string personelType = rootANode.Attributes["mqcode"].Value;
                //        XmlNodeList targetNodes = item.SelectNodes( partXPath);
                //        if (targetNodes.Count > 0)
                //        {
                //            if (_dataContext.DataLayerAns.CaseType.ToLower() == "a1")
                //            {
                //                re.Add(rootANode.Attributes["configeName"].Value + "@" + personelType, targetNodes[0].Attributes["paragCode"].Value);

                //            }
                //            else
                //            {
                //                re.Add(rootANode.Attributes["configeName"].Value + "@" + personelType, targetNodes[0].Attributes["paragCode"].Value);

                //            }
                //        }


                //    }
                //}

            }

            //string xml = "<root><parties mqcode=\"exd_mscourtrecord,dan_sub\" zh_info=\"当事人对话段落配置\" configeName=\"SuitDegreeID\" type=\"b1\"><b1><mssuitbook paragCode=\"MS_IM_SuitParticipant\" /><mscourtrecord paragCode=\"MS_CR_SuitParticipant\" /></b1></parties><parties mqcode=\"ws010000143_renyuan\" zh_info=\"当事人对话段落配置\" configeName=\"SuitDegreeID\" type=\"jb1\"><jb1><ws010000143 paragCode=\"jb1_PO_Participant\" /></jb1></parties><parties mqcode=\"xsrenyuan_sub\" zh_info=\"当事人对话段落配置\" configeName=\"SuitDegreeID\" type=\"a1\"><a1><xscourtrecord paragCode=\"XS_CR_SuitParticipant\" /></a1></parties><judge mqcode=\"exd_mscourtrecord_judge_sub\" zh_info=\"审理人对话段落配置\" configeName=\"TP_IdentityID\"><b1><mscourtrecord paragCode=\"MS_CR_Header,MS_CR_Trailer\" /></b1></judge></root>";
            //xml = "<root><parties mqcode=\"renyuan_entity\" zh_info=\"当事人对话段落配置\" configeName=\"SuitDegreeID\" type=\"b1\"><b1><mssuitbook paragCode=\"MS_IM_SuitParticipant\" /><mscourtrecord paragCode=\"MS_CR_SuitParticipant\" /></b1></parties><parties mqcode=\"renyuan_entity\" zh_info=\"当事人对话段落配置\" configeName=\"SuitDegreeID\" type=\"jb1\"><jb1><ws010000143 paragCode=\"jb1_PO_Participant\" /></jb1></parties><parties mqcode=\"renyuan_entity\" zh_info=\"当事人对话段落配置\" configeName=\"SuitDegreeID\" type=\"a1\"><a1><xscourtrecord paragCode=\"XS_CR_SuitParticipant\" /></a1></parties><judge mqcode=\"exd_mscourtrecord_judge_sub\" zh_info=\"审理人对话段落配置\" configeName=\"TP_IdentityID\"><b1><mscourtrecord paragCode=\"MS_CR_Header,MS_CR_Trailer\" /></b1></judge></root>";
            //52专用
            
            if (re.Count == 0 && _dataContext.DataLayerAns.SourceCode.ToLower() == "ws010003662")
            {
                re.Add("SuitDegreeID@exd_borrowcontract_person", "MS_BC_Participant");
            }
            return re;

        }

        /// <summary>
        /// 计算人员角色下标
        /// </summary>
        /// <param name="SuitDegreeID"></param>
        /// <returns></returns>
        private int PersonnelReadIndex(string SuitDegreeID)
        {
            int ReadIndex = 0;
            if (_dataContext.DataLayerAns.Anjianshitis != null)
            {
                List<An_anjianshiti> anjianshitiList = _dataContext.DataLayerAns.Anjianshitis.
                    Where(a => a.Anjianshitijueses.IndexOf(a.Anjianshitijueses.FirstOrDefault(f => f.Juesesusongdiwei == SuitDegreeID)) > -1).ToList();

                List<An_anjianshitijuese> anjianshitijueseList = new List<An_anjianshitijuese>();
                foreach (An_anjianshiti itmecase in anjianshitiList)
                {
                    anjianshitijueseList.AddRange(itmecase.Anjianshitijueses);
                }
                ReadIndex = anjianshitijueseList.Count + 1;
            }
            return ReadIndex;
        }

        #endregion
    }

    public class PersonPostModle
    {
        public string id { get; set; }

        public string modelCode { get; set; }

        public string content { get; set; }
    }
}
